# backend/repositories/user_repo.py
from sqlalchemy.orm import Session
from app.models.coop_app.user import User
from app.schema.user_schema import UserCreate, UserUpdate,UpdateUserInfoRequest
import uuid
from passlib.hash import bcrypt
from typing import Optional
from typing import List
from sqlalchemy.orm import joinedload
from app.models.coop_app.user_permission import UserPermission

def get_user_by_email(db: Session, email: str) -> Optional[User]:
    return db.query(User).filter(User.email == email).first()


def get_user_by_id(db: Session, user_id: str) -> Optional[User]:
    return db.query(User).filter(User.user_id == user_id).first()


def get_user_by_id(db: Session, user_id: str):
    return db.query(User).filter(User.user_id == user_id).options(
        joinedload(User.role),
        joinedload(User.permissions).joinedload(UserPermission.permission) # new code
    ).first()

def get_users_paginated(db: Session, skip: int = 0, limit: int = 10):
    return (
        db.query(User)
        .options(joinedload(User.permissions))  
        .offset(skip)
        .limit(limit)
        .all()
    )

def count_users(db: Session) -> int:
    return db.query(User).count()


def get_user_list(db: Session, skip: int = 0, limit: int = 10) -> List[User]:
    return db.query(User).offset(skip).limit(limit).all()

def update_password(db: Session, user: User, new_password: str) -> User:
    user.password_hash = bcrypt.hash(new_password)
    db.commit()
    db.refresh(user)
    return user


def create_user(db: Session, user: UserCreate) -> User:
    new_user = User(
        user_id=str(uuid.uuid4()),
        first_name=user.first_name,
        last_name=user.last_name,
        email=user.email,
        role_id=2,
        password_hash=bcrypt.hash(user.password)
    )
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user


def update_user(db: Session, user_id: str, user_update: UserUpdate) -> Optional[User]:
    user = get_user_by_id(db, user_id)
    if not user:
        return None
    if user_update.first_name:
        user.first_name = user_update.first_name
    if user_update.last_name:
        user.last_name = user_update.last_name
    if user_update.password:
        user.password_hash = bcrypt.hash(user_update.password)
    db.commit()
    db.refresh(user)
    return user


def delete_user(db: Session, user_id: str) -> bool:
    user = get_user_by_id(db, user_id)
    if not user:
        return False
    db.delete(user)
    db.commit()
    return True


def update_user_info(db: Session, user: User, update_data: UpdateUserInfoRequest) -> User:
    if update_data.first_name is not None:
        user.first_name = update_data.first_name
    if update_data.last_name is not None:
        user.last_name = update_data.last_name
    if update_data.email is not None:
        user.email = update_data.email

    db.commit()
    db.refresh(user)
    return user


